﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;
using HtmlAgilityPack;
using log4net;

namespace 百度云搜索神器
{
    public partial class BaiduCloudSearch : Form
    {
        private static ILog _log = LogManager.GetLogger(typeof(BaiduCloudSearch));
        public BaiduCloudSearch()
        {
            Control.CheckForIllegalCrossThreadCalls = false;
            InitializeComponent();
        }
        HtmlAgilityPack.HtmlDocument doc = new HtmlAgilityPack.HtmlDocument(); //用于解析html对象
        private void button1_Click(object sender, EventArgs e)
        {
            try
            {
                if (GetLength(textBox1.Text)<= 3)
                {
                    label2.Text = "用户操作：输入的内容必须大于2个汉字 （4字节）";
                    return;
                }
                listView1.Items.Clear();
                Thread Thd = new Thread(TestMethod);
                Thd.Start();
            }
            catch (Exception ex)
            {
                _log.Error(ex.Message);
                Environment.Exit(Environment.ExitCode); 
            }
        }
        public static int GetLength(string str)
        {
            if (str.Length == 0) return 0;
            ASCIIEncoding ascii = new ASCIIEncoding();
            int tempLen = 0;
            byte[] s = ascii.GetBytes(str);
            for (int i = 0; i < s.Length; i++)
            {
                if ((int)s[i] == 63)
                {
                    tempLen += 2;
                }
                else
                {
                    tempLen += 1;
                }
            }
            return tempLen;
        }
        HtmlAgilityPack.HtmlDocument htmldoc = new HtmlAgilityPack.HtmlDocument();
        void TestMethod()
        {
            try
            {
                this.listView1.Items.Clear();
                this.ControlBox = false;
                textBox1.Enabled = false;
                progressBar1.Value = 0;
                List<Data> DataList = new List<Data>();  //保存html数据的集合
                for (int ye = 0; ye != 15; ++ye)
                {               
                    string str = "";
                    if (ye > 1)
                    {
                         str = geihtml(@"http://www.pansoso.com/zh/" + @textBox1.Text + "/_" + ye.ToString());
                    }
                    else
                    {
                        str = geihtml(@"http://www.pansoso.com/zh/" + @textBox1.Text);                     
                    }
                    String[] Data = Regex.Split(str, "searleft", RegexOptions.IgnoreCase);                    
                    htmldoc.LoadHtml(str);
                    HtmlNode node1 = htmldoc.GetElementbyId("content");
                    if (node1 == null)
                    {
                        node1 = htmldoc.GetElementbyId("con");
                        foreach(var childNode in node1.ChildNodes)
                        {
                            if (childNode.Name != "div")
                            {
                            string[] data = ReturnData(childNode.InnerText);
                            string url = "http://www.pansoso.com" + GetTitleContent(childNode.OuterHtml, "a", "href");
                            DataList.Add(new Data() { FileName = data[0], FileSize = data[1], SharePeople = data[2], ShareTime = data[3], SeeNum = data[4], Url = url });
                            ListViewItem lvi = new ListViewItem();
                            
                            lvi.SubItems.Add(data[0]);
                            lvi.SubItems.Add(data[1]);
                            lvi.SubItems.Add(data[2]);
                            lvi.SubItems.Add(data[3]);
                            lvi.SubItems.Add(data[4]);

                            // lvi.SubItems.Add(data[4]);
                            lvi.SubItems.Add(url);
                            lvi.SubItems.RemoveAt(0);
                            listView1.Items.Add(lvi);
                            }
                        }
                    }
                    else
                    {
                        foreach (var ChildNode in node1.ChildNodes)
                        {

                            //if (ChildNode.Id == "content")
                            //{
                            string[] data = ReturnData(ChildNode.InnerText);
                            string url = "http://www.pansoso.com" + GetTitleContent(ChildNode.OuterHtml, "a", "href");
                            DataList.Add(new Data() { FileName = data[0], FileSize = data[1], SharePeople = data[2], ShareTime = data[3], SeeNum = data[4], Url = url });
                            ListViewItem lvi = new ListViewItem();
                            lvi.SubItems.Add(data[0]);
                            lvi.SubItems.Add(data[1]);
                            lvi.SubItems.Add(data[3]);
                            lvi.SubItems.Add(data[4]);
                            lvi.SubItems.Add(data[2]);
                            
                            lvi.SubItems.Add(url);
                            listView1.Items.Add(lvi);
                            //}
                        }
                    }
                    if (progressBar1.Value != 15)
                    {
                        progressBar1.Value = ++progressBar1.Value;
                        label2.Text = "用户操作：正在为您努力磨叽……剩余叽叽：（" + Convert.ToString(67 - Convert.ToInt32( progressBar1.Value)) + ")";
                    }
                }
                label2.Text = "用户操作：双击即可打开指定的文件下载地址哦！";
                textBox1.Enabled = true;
                this.ControlBox = true;
            }
            catch (Exception ex)
            {
                _log.Error(ex.Message);
                Environment.Exit(Environment.ExitCode); 
            }
            
        } //线程
        private string geihtml(string url)
        {
            /// <获取网页源码>
            /// <param name="Url">链接</param>
            /// <param name="CharSet">编码</param>
            try
            {
                WebClient hl = new WebClient();
                byte[] hltext = hl.DownloadData(url);//取网页源码
                return (Encoding.GetEncoding("UTF-8").GetString(hltext));//编码转换
            }
            catch (Exception ex)
            {
                _log.Error(ex.Message);
                return "错误";
            }
        }
        //截取字符串
        private string[] ReturnData(string message)
        {

            string[] data2 = new string[5];
            string[] data = message.Split(',');
            for (int i = 0; i < data2.Count(); i++)
            {
                int index = data[i].IndexOf(':') + 1;
                data2[i] = data[i].Remove(0, index);
            }
            return data2;

        }
        //获取网盘的URL
        /// <summary>  
        /// 获取字符中指定标签的值  
        /// </summary>  
        /// <param name="str">字符串</param>  
        /// <param name="title">标签</param>  
        /// <param name="attrib">属性名</param>  
        /// <returns>属性</returns>  
        public static string GetTitleContent(string str, string title, string attrib)
        {

            string tmpStr = string.Format("<{0}[^>]*?{1}=(['\"\"]?)(?<url>[^'\"\"\\s>]+)\\1[^>]*>", title, attrib); //获取<title>之间内容  

            Match TitleMatch = Regex.Match(str, tmpStr, RegexOptions.IgnoreCase);

            string result = TitleMatch.Groups["url"].Value;
            return result;
        }    
        private void listView1_ColumnWidthChanging(object sender, ColumnWidthChangingEventArgs e)
        {
            try
            {
                if (e.ColumnIndex == 3)
                {
                    ColumnHeader header = this.listView1.Columns[e.ColumnIndex];
                    e.NewWidth = listView1.Columns[e.ColumnIndex].Width;
                    e.Cancel = true;
                }
            }
            catch (Exception ex)
            {
                _log.Error(ex.Message);
                Environment.Exit(Environment.ExitCode); 
            }
        }

        private void Form1_FormClosing(object sender, FormClosingEventArgs e)
        {
            //System.Environment.Exit(System.Environment.ExitCode); 
            this.Dispose();           
        }

        private void listView1_DoubleClick(object sender, EventArgs e)
        {
            int length = listView1.SelectedItems.Count;
            for (int i = 0; i < length; i++)
            {
                Process.Start(listView1.SelectedItems[i].SubItems[5].Text);
            }
        }
        private void Form1_FormClosed(object sender, FormClosedEventArgs e)
        {         
        }

        //private void listView1_DoubleClick(object sender, EventArgs e)
        //{
        //   
        //}
    }
    public class Data
    {
        public string FileName { get; set; }   //文件名
        public string FileSize { get; set; }   //文件大小
        public string SharePeople { get; set; }  //分享者
        public string ShareTime { get; set; }   //分享时间
        public string SeeNum { get; set; }    //浏览次数
        public string Url { get; set; }       //下载的URL
    }
}
